package com.atguigu.guli.api.gateway.handler;

import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

public class GlobalJsonExceptionHandler extends DefaultErrorWebExceptionHandler {

    public GlobalJsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }
    //指定异常响应采用Json处理
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all() ,this::renderErrorResponse );
    }
    //配置响应体内容
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        int code = ResultCodeEnum.UNKNOWN_REASON.getCode();
        Throwable error = getError(request);
        if(error instanceof org.springframework.cloud.gateway.support.NotFoundException){
            code = ResultCodeEnum.PATH_ERROR.getCode();
        }
        String message  = error.getMessage();
        //封装异常响应报文数据
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("message", message);
        map.put("data", null);
        return map;
    }

    //响应报文获取状态码
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {

        return 200;
    }
}